import java.io.*;
import java.net.*;
import java.util.Arrays;

public class ForwarderTest_UDPReceiver {
    private static final int BUFFER_SIZE = 1024;

    public static byte[] getBytes(byte[] source, int offset, int length) {
        if (offset < 0 || length < 0 || offset + length > source.length) {
            throw new IllegalArgumentException("Invalid offset or length");
        }
        return Arrays.copyOfRange(source, offset, offset + length);
    }

    public static void main(String[] args) {
        if (args.length != 3) {
            System.out.println("Usage: java ForwarderTest_Receiver <host> <port> <output_file>");
            return;
        }

        String host = args[0];
        int port = Integer.parseInt(args[1]);
        String outputFile = args[2];

        try {
            MulticastSocket socket = new MulticastSocket(port);
            InetAddress group = InetAddress.getByName(host);
            socket.joinGroup(group);
            FileOutputStream fos = new FileOutputStream(outputFile);

            byte[] buffer = new byte[BUFFER_SIZE];
            System.out.println("Waiting for file on port " + port + "...");

            while (true) {
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                socket.receive(packet);

                byte[] receivedBytes = getBytes(packet.getData(), 0, packet.getLength());
                for (String s: Utils.bytesToHexList(receivedBytes))
                {
                    System.out.println(s);
                }
                String receivedData = new String(packet.getData(), 0, packet.getLength());
                if (receivedData.equals("END")) {
                    break;
                }

                fos.write(packet.getData(), 0, packet.getLength());
                System.out.print(".");
            }
            System.out.println("\nFile received and saved as: " + outputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
